local AtlasLoot = LibStub("AceAddon-3.0"):GetAddon("AtlasLoot")
local AL = LibStub("AceLocale-3.0"):GetLocale("AtlasLoot")
local GREY = "|cff999999"
local RED = "|cffff0000"
local WHITE = "|cffFFFFFF"
local GREEN = "|cff1eff00"
local PURPLE = "|cff9F3FFF"
local BLUE = "|cff0070dd"
local ORANGE = "|cffFF8400"
local DEFAULT = "|cffFFd200"
local ParseTooltip_Enabled = false

local AltasLootItemButton = {}

-- AtlasLoot:CreateItemButton
do
	local mt = {__index = AltasLootItemButton}
	-- Creat a AtlasLoot ItemButton with:
	-- frames:		Icon, Name, ExtraText, Unsafe
	-- functions: 	SetButtonType, GetItemEquipInfo, Clear, Refresh, SetItem, SetSpell, SetLink
	-- for usage of the functions check the AltasLootItemButton table
	-- @param parent The parent frame where the ItemButton is created
	-- @param point Sets the itemButton Position. This use frame:SetPoint(...)
	-- @param name The name of the ButtonFrame
	-- @return The itemButton
	-- @usage itemButton = AtlasLoot:CreateItemButton("AtlasLootItemsFrame", {"TOPLEFT", Frame, "TOPLEFT", 25, -35}, "AtlasLootItem_1")
	function AtlasLoot:CreateItemButton(parent, point, name)
		parent = parent or UIParent
		if not point or type(point) ~= "table" then point = {"TOPLEFT", parent, "TOPLEFT", 0, 0} end
		if not name or name == "" then
			--error("AtlasLoot:CreateItemButton: Enter a name.", 2)
			return
		end

		-- Set the metaTable
		local itemButton = setmetatable(
			{
				Frame = {},
				item = false,
				spell = false,
				tableLink = false,				
			},
			mt
		)
		
		-- ########################
		-- Create the itemFrame
		-- ########################
			
		-- MainFrame <frame>
		itemButton.Frame = CreateFrame("Button", name, parent)
		itemButton.Frame:SetWidth(236)
		itemButton.Frame:SetHeight(28)
		itemButton.Frame:SetPoint(unpack(point));
		itemButton.Frame:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight", "ADD")
		itemButton.Frame:RegisterForClicks("LeftButtonDown", "RightButtonDown")	
		itemButton.SetPoint = itemButton.Frame.SetPoint
			
		-- Icon <texture>
		itemButton.Frame.Icon = itemButton.Frame:CreateTexture(name.."_Icon", "ARTWORK")
		itemButton.Frame.Icon:SetPoint("TOPLEFT", itemButton.Frame, "TOPLEFT", 1, -1)
		itemButton.Frame.Icon:SetHeight(25)
		itemButton.Frame.Icon:SetWidth(25)	
		
		-- Menu icon <texture>
		itemButton.Frame.MenuIcon = itemButton.Frame:CreateTexture(name.."_MenuIcon", "ARTWORK")
		itemButton.Frame.MenuIcon:SetPoint("TOPLEFT", itemButton.Frame, "TOPLEFT", 3, -3)
		itemButton.Frame.MenuIcon:SetHeight(20)
		itemButton.Frame.MenuIcon:SetWidth(20)
		
		-- Menu IconBorder <texture>
		itemButton.Frame.MenuIconBorder = itemButton.Frame:CreateTexture(nil, "OVERLAY")
		itemButton.Frame.MenuIconBorder:SetPoint("TOPLEFT", itemButton.Frame.MenuIcon, "TOPLEFT", -5, 5)
		itemButton.Frame.MenuIconBorder:SetTexture("Interface\\Minimap\\MiniMap-TrackingBorder")
		itemButton.Frame.MenuIconBorder:SetHeight(52)
		itemButton.Frame.MenuIconBorder:SetWidth(52)
			
		-- Query Icon <texture>
		itemButton.Frame.QueryIcon = itemButton.Frame:CreateTexture(name.."_QueryIcon", "OVERLAY")
		itemButton.Frame.QueryIcon:SetPoint("TOPLEFT", itemButton.Frame.Icon, "TOPLEFT", 0, 0)
		itemButton.Frame.QueryIcon:SetTexture("Interface\\AddOns\\AtlasLoot\\Images\\arrow")
		itemButton.Frame.QueryIcon:SetHeight(25)
		itemButton.Frame.QueryIcon:SetWidth(25)
		itemButton.Frame.QueryIcon:Hide()		
			
		-- ItemName <FontString>
		itemButton.Frame.Name = itemButton.Frame:CreateFontString(name.."_Name", "ARTWORK", "GameFontNormal")
		itemButton.Frame.Name:SetPoint("TOPLEFT", itemButton.Frame.Icon, "TOPRIGHT", 3, 0)
		itemButton.Frame.Name:SetJustifyH("LEFT")
		itemButton.Frame.Name:SetText("")
		itemButton.Frame.Name:SetWidth(205)
		itemButton.Frame.Name:SetHeight(12)
			
		-- ExtraText <FontString>		
		itemButton.Frame.Extra = itemButton.Frame:CreateFontString(name.."_Extra", "ARTWORK", "GameFontNormalSmall")
		itemButton.Frame.Extra:SetPoint("TOPLEFT", itemButton.Frame.Name, "BOTTOMLEFT", 0, -1)
		itemButton.Frame.Extra:SetJustifyH("LEFT")
		itemButton.Frame.Extra:SetText("")
		itemButton.Frame.Extra:SetWidth(205)
		itemButton.Frame.Extra:SetHeight(10)
		
		-- Extra text for Quests/Achievements
		itemButton.Frame.QA = CreateFrame("Button", name.."_QA", itemButton.Frame)
		itemButton.Frame.QA:SetWidth(205)
		itemButton.Frame.QA:SetHeight(14)
		itemButton.Frame.QA:SetPoint("TOPLEFT", itemButton.Frame.Name, "BOTTOMLEFT", 0, -1)
		itemButton.Frame.QA:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight", "ADD")
		itemButton.Frame.QA:RegisterForClicks("LeftButtonDown", "RightButtonDown")	
		
		itemButton.Frame.QA.ExtraIcon = itemButton.Frame.QA:CreateTexture(name.."_QAExtraIcon", "OVERLAY")
		itemButton.Frame.QA.ExtraIcon:SetPoint("TOPLEFT", itemButton.Frame.QA, "TOPLEFT", 0, -1)
		itemButton.Frame.QA.ExtraIcon:SetTexture("Interface\\Icons\\INV_Misc_QuestionMark")
		itemButton.Frame.QA.ExtraIcon:SetHeight(10)
		itemButton.Frame.QA.ExtraIcon:SetWidth(10)
		
		--- text
		itemButton.Frame.QA.ExtraText = itemButton.Frame.QA:CreateFontString(name.."_QAExtraText", "ARTWORK", "GameFontNormalSmall")
		itemButton.Frame.QA.ExtraText:SetPoint("TOPLEFT", itemButton.Frame.QA, "TOPLEFT", 12, -1)
		itemButton.Frame.QA.ExtraText:SetJustifyH("LEFT")
		itemButton.Frame.QA.ExtraText:SetText("TEST")
		itemButton.Frame.QA.ExtraText:SetWidth(205)
		itemButton.Frame.QA.ExtraText:SetHeight(10)
		
		itemButton.Frame.QA:SetScript("OnEnter", AtlasLoot.QAItemOnEnter)
		itemButton.Frame.QA:SetScript("OnLeave", AtlasLoot.QAItemOnLeave)
		itemButton.Frame.QA:SetScript("OnClick", AtlasLoot.QAItemOnClick)
		
		-- Unsafe <texture>
		itemButton.Frame.Unsafe = itemButton.Frame:CreateTexture(name.."_Unsafe", "BACKGROUND")
		itemButton.Frame.Unsafe:SetPoint("TOPLEFT", itemButton.Frame, "TOPLEFT")
		itemButton.Frame.Unsafe:SetHeight(27)
		itemButton.Frame.Unsafe:SetWidth(27)
		itemButton.Frame.Unsafe:SetTexture(1,0,0,1)
		itemButton.Frame.Unsafe:Hide()		
			
		-- itemButton Scripts
		itemButton.Frame:SetScript("OnEnter", AtlasLoot.ItemOnEnter)
		itemButton.Frame:SetScript("OnLeave", AtlasLoot.ItemOnLeave)
		itemButton.Frame:SetScript("OnClick", AtlasLoot.ItemOnClick)
		itemButton.Frame:SetScript("OnShow", function() itemButton.Frame:SetFrameLevel( (itemButton.Frame:GetParent()):GetFrameLevel() + 1 ) end)
		itemButton.Frame:SetScript("OnEvent", AtlasLoot.ItemOnEvent)
		itemButton.Frame.par = itemButton
		-- Hide the button
		itemButton.Frame:Hide()

		return itemButton	
	end
end

--- Sets the type of the button
-- AtlasLoot needs self, too check what things the button can do :o
-- @param item Button contains a item
-- @param spell Button contains a spell
-- @param tableLink TableLink to another loottable
-- @usage AltasLootItemButton:SetButtonType(true, true, nil)
function AltasLootItemButton:SetButtonType(item, spell, tableLink)
	if item then
		self.item = true
	elseif item == "" then
		self.item = self.item
	else
		self.item = false
	end
	if spell then
		self.spell = true
	elseif spell == "" then
		self.spell = self.spell
	else
		self.spell = false
	end
	if tableLink then
		self.tableLink = tableLink
	elseif tableLink == "" then
		self.tableLink = self.tableLink
	else
		self.tableLink = nil
	end
end

-- Set functions
do
	local dummyIcon = "Interface\\Icons\\INV_Misc_QuestionMark"
	local questIcon = "Interface\\MINIMAP\\TRACKING\\TrivialQuests"
	local achievementIcon = "Interface\\ACHIEVEMENTFRAME\\UI-Achievement-TinyShield"
	
	local function GetAchievementOrQuestText(text)
		local tempText, isQuest, isAchievement = nil, nil, nil
		if text and string.find(text, "#QUESTID:%d+#") then
			_,_,isQuest = string.find(text, "#QUESTID:(%d+)#")
			tempText = AtlasLoot:GetQuestName(isQuest)
			tempText = "|cffFFFFFF"..tempText
			tempText = gsub(text, "#QUESTID:%d+#", tempText)
		elseif text and string.find(text, "#ACHIEVEMENTID:%d+#") then
			_,_,isAchievement = string.find(text, "#ACHIEVEMENTID:(%d+)#")
			if GetAchievementLink(isAchievement) then
				tempText = select(2,GetAchievementInfo(isAchievement))
			else
				tempText = "ID:"..isAchievement.." not found"
			end
			tempText = "|cff1eff00"..tempText
			tempText = gsub(text, "#ACHIEVEMENTID:%d+#", tempText)
		end
		
		return tempText, isQuest, isAchievement
	end
	
	-- Create and returns the editet extra Text
	local function GetItemExtraText(itemID, extraText, price, itemName)
		local tempText, isQuest, isAchievement = nil, nil, nil
		--[[
		if extraText and string.find(extraText, "#QUESTID:%d+#") then
			_,_,isQuest = string.find(extraText, "#QUESTID:(%d+)#")
			tempText = AtlasLoot:GetQuestName(isQuest)
			tempText = "|cffFFFFFF"..tempText
			tempText = gsub(extraText, "#QUESTID:%d+#", tempText)
		elseif extraText and string.find(extraText, "#ACHIEVEMENTID:%d+#") then
			_,_,isAchievement = string.find(extraText, "#ACHIEVEMENTID:(%d+)#")
			if GetAchievementLink(isAchievement) then
				tempText = select(2,GetAchievementInfo(isAchievement))
			else
				tempText = "ID:"..isAchievement.." not found"
			end
			tempText = "|cff1eff00"..tempText
			tempText = gsub(extraText, "#ACHIEVEMENTID:%d+#", tempText)
		end
		]]
		tempText, isQuest, isAchievement = GetAchievementOrQuestText(extraText)
		local tempPrice = GetAchievementOrQuestText(price)
		if not tempText and extraText and price and price ~= "" then
			-- lengh < 70  = standart
			-- this adds the ItemPrice to the Extratext if its not to long
			if AtlasLoot.db.profile.ShowPriceAndDesc and price ~= "=ds=" and price ~= "" then
				if extraText == "=ds=" or extraText == "" then
					if itemName then
						extraText = AtlasLoot:GetItemEquipInfo(itemID)
					else
						extraText = price
					end
				end
				local dummyText = AtlasLoot:FixText(extraText).." / "..price
				local lengh = string.len(dummyText)
				if lengh < 50 then
					tempText = dummyText
				end
			end
			if not tempText or tempText == "" then
				if extraText == "=ds=" or extraText == "" then
					if itemName then
						extraText = AtlasLoot:GetItemEquipInfo(itemID)
					else
						extraText = price
					end
				end
				if price == "=ds=" or price == "" then
					price = extraText
				end

				if AtlasLoot.db.profile.ShowLootTablePrice then
					if tempPrice then
						tempText, isQuest, isAchievement = GetAchievementOrQuestText(price)
					else
						tempText = price
					end
				else
					tempText = extraText
				end
			end
		elseif not tempText and price and price ~= "" then
			--if tempPrice then
			--	price, isQuest, isAchievement = GetAchievementOrQuestText(extraText)
			--end
			--tempText = price
		elseif not tempText and extraText then
			tempText = extraText
		elseif not tempText and not extraText and itemName then
			tempText = AtlasLoot:GetItemEquipInfo(itemID)
		end
		
		tempText = AtlasLoot:FixText(tempText)
		return tempText or "", isQuest, isAchievement
	end

	local function Setup_ItemExtraText(self, itemID, extraText, itemPrice, itemNameNew)
		local tempText, isQuest, isAchievement = GetItemExtraText(itemID, extraText, itemPrice, itemNameNew)
		
		if isQuest then
			self.Frame.Extra:Hide()
			self.Frame.QA:Show()
			self.Frame.QA.questID = isQuest
			self.Frame.QA.ExtraIcon:SetTexture(questIcon)
			self.Frame.QA.ExtraIcon:SetWidth(10)
			self.Frame.QA.ExtraIcon:SetHeight(10)	
			self.Frame.QA.ExtraText:SetPoint("TOPLEFT", self.Frame.QA, "TOPLEFT", 10, -1)
			self.Frame.QA.ExtraText:SetText(tempText)
		elseif isAchievement then
			self.Frame.Extra:Hide()
			self.Frame.QA:Show()
			self.Frame.QA.achievementID = isAchievement
			self.Frame.QA.ExtraIcon:SetTexture(achievementIcon)
			self.Frame.QA.ExtraIcon:SetWidth(20)
			self.Frame.QA.ExtraIcon:SetHeight(20)	
			self.Frame.QA.ExtraText:SetPoint("TOPLEFT", self.Frame.QA, "TOPLEFT", 12, -1)
			self.Frame.QA.ExtraText:SetText(tempText)		
		else
			self.Frame.QA:Hide()
			self.Frame.Extra:SetText(tempText)
			self.Frame.Extra:Show()		
		end
	end
	--- Sets a item to the button
	-- @param itemID The item ID
	-- @param itemName The item name, self is only used if the item name is not in the cache. Set to nil and not in cache it will use UNKNOWN
	-- @param extraText The small text under the item name. Set to nil and it will use slotInfo of the item if aviable
	-- @param itemTexture Sets a texture for the item icon. Set to nil and it will use the icon from the item ID
	-- @param itemPrice The item price (Arena, PVP, ...). Set self will hide the extra text if its to long
	-- @param itemDroprate The droprate of the item. Only a number value automatic adds "%"
	-- @usage AltasLootItemButton:SetItem(45038, "=q5=Fragment of Val'anyr", "=ds=#m3#", nil, nil, "40%")
	function AltasLootItemButton:SetItem(itemID, itemName, extraText, itemTexture, itemPrice, itemDroprate)
		self:Clear()
		if not itemID or type(itemID) ~= "number" then
			self:SetDummy(itemName, extraText, itemTexture)
			--error("AltasLootItemButton:SetItem: Enter a itemID <number>", 2)
			return
		end
		if not self.info then
			self.info = { nil, itemID, itemName, extraText, itemTexture, itemPrice, itemDroprate }
		end
		
		self:SetButtonType(true, false, nil)
		self.Frame:Show()
		local tempText = ""
		local itemNameNew, itemLink, itemQuality, itemLevel, itemMinLevel, itemType, itemSubType, itemCount, itemEquipLoc, itemTextureNew = GetItemInfo(itemID)
		itemTextureNew = GetItemIcon(itemID)
		if not itemTextureNew then
			itemTextureNew = "Interface\\Icons\\INV_Misc_QuestionMark"
		end
		
		-- ########################
		-- itemName
		-- ########################
		if itemNameNew then
			_, _, _, itemQuality = GetItemQualityColor(itemQuality)
			tempText = itemQuality..string.gsub(itemNameNew, 1, 4)
		elseif itemName then
			tempText = AtlasLoot:FixText(itemName)
		else
			tempText = _G["UNKNOWN"]
		end
		self.Frame.Name:SetText(tempText)
		tempText = ""

		-- ########################
		-- extraText and itemPrice
		-- ########################
		Setup_ItemExtraText(self, itemID, extraText, itemPrice, itemNameNew)
		
		-- ########################
		-- itemTexture
		-- ########################
		if itemTexture == "?" then
			self:SetIcon("Interface\\Icons\\INV_Misc_QuestionMark")
		elseif itemTexture and type(itemTexture) == "string" and itemTexture ~= "" then
			self:SetIcon(itemTexture)
		else
			self:SetIcon(itemTextureNew)
		end
		
		-- ########################
		-- itemDroprate
		-- ########################
		if itemDroprate then
			if type(itemDroprate) == "number" then
				self.droprate = itemDroprate.."%"
			else
				self.droprate = itemDroprate
			end
		end
		
		-- ########################
		-- Unsafe
		-- ########################
		if not GetItemInfo(itemID) and itemID and itemID ~= 0 then
			self.Frame.Unsafe:Show()
		end
	end

	--- Sets a spell to the button
	-- @param spellID The spell ID
	-- @param itemID The item ID from the crafted spell
	-- @param spellName The spell name, self is only used if the spell name is not in the cache. Set to nil and not in cache it will use UNKNOWN
	-- @param extraText The small text under the spell name.
	-- @param itemTexture Sets a texture for the spell icon. Set to nil and it will use the icon from the spell ID
	-- @param itemPrice The item price (Arena, PVP, ...). Set self will hide the extraText if its to long
	-- @usage AltasLootItemButton:SetSpell(60403, 44323, "=q3=Indestructible Alchemist Stone", "=ds="..AL["Trainer"], nil, nil)
	function AltasLootItemButton:SetSpell(spellID, itemID, spellName, extraText, spellTexture, itemPrice)
		self:Clear()
		if not spellID or type(spellID) ~= "number" then
			self:SetDummy(spellName, extraText, spellTexture)
			--error("AltasLootItemButton:SetSpell: Enter a spellID <number>", 2)
			return
		end
		if not self.info then
			self.info = { spellID, itemID, spellName, extraText, spellTexture, itemPrice, nil }
		end
		self.Frame:Show()
		local tempText = ""
		local spellNameNew, _, spellTextureNew = GetSpellInfo(spellID)
		if itemID then
			spellTextureNew = GetItemIcon(itemID)
		end
		self:SetButtonType(false, true, nil)
		
		-- ########################
		-- spellName
		-- ########################
		if spellNameNew then
			tempText = AtlasLoot:FixText(string.sub(spellName, 1, 4)..spellNameNew)
		elseif spellName then
			tempText = AtlasLoot:FixText(spellName)
		else
			tempText = _G["UNKNOWN"]
		end
		self.Frame.Name:SetText(tempText)
		tempText = ""
		
		-- ########################
		-- extraText and itemPrice
		-- ########################
		Setup_ItemExtraText(self, itemID, extraText, itemPrice, spellNameNew)
		
		-- ########################
		-- itemTexture
		-- ########################
		if spellTexture == "?" then
			self:SetIcon("Interface\\Icons\\INV_Misc_QuestionMark")
		elseif spellTexture and type(spellTexture) == "string" and spellTexture ~= "" then
			self:SetIcon(spellTexture or dummyIcon)
		else
			self:SetIcon(spellTextureNew or dummyIcon)
		end
		
		-- ########################
		-- Unsafe
		-- ########################
		if not spellNameNew then
			self.Frame.Unsafe:Show()
		end
	end
	
	--- Sets a clickable MenuButton
	-- @param linkTab The AtlasLoot table name that open on click
	-- @param tabName The name of the table. Set to nil an it use the tableName
	-- @param tabExtraText The small text under the table name.
	-- @param iconTexture path to icon texture
	function AltasLootItemButton:SetMenu(linkTab, tabName, tabExtraText, iconTexture, tableLinkFunc)
		self:Clear()
		self.tableLinkFunc = tableLinkFunc
		self:SetLink(linkTab)
		if not self.tableLink then
			self:SetDummy(tabName, tabExtraText, iconTexture)
			--error("AltasLootItemButton:SetMenu: Enter a available AtlasLoot table <string> ", 2)
			return
		end
		if not self.info then
			self.info = { nil, nil, tabName, tabExtraText, iconTexture, nil, nil }
		end
		self:SetButtonType(false, false, linkTab)
		self.Frame:Show()
		local tempText = ""
		-- ########################
		-- tabName
		-- ########################
		if tabName then
			tempText = AtlasLoot:FixText(tabName)
		else
			if AtlasLoot_Data[linkTab].info.name then
				tempText = AtlasLoot_Data[linkTab].info.name
			end
		end
		self.Frame.Name:SetText(tempText)
		tempText = ""
		
		-- ########################
		-- tabExtraText
		-- ########################
		Setup_ItemExtraText(self, nil, tabExtraText, nil, nil)
		
		-- ########################
		-- itemTexture
		-- ########################
		if iconTexture == "?" then
			self:SetIcon("Interface\\Icons\\INV_Misc_QuestionMark")
		elseif iconTexture and type(iconTexture) == "string" and iconTexture ~= "" then
			self:SetIcon(iconTexture)
		else
			self:SetIcon("Interface\\Icons\\INV_Misc_QuestionMark")
		end
		
		-- ########################
		-- Unsafe
		-- ########################
		self.Frame.Unsafe:Hide()
	end

	--- Sets a dummy button
	-- self button only have text and a icon
	-- @param name The name
	-- @param extraText The small text under the name.
	-- @param iconTexture path to icon texture
	function AltasLootItemButton:SetDummy(name, extraText, iconTexture)
		self:Clear()
		self.Frame:Show()
		
		local tempText = ""
		-- ########################
		-- name
		-- ########################
		tempText = AtlasLoot:FixText(name or "")
		
		self.Frame.Name:SetText(tempText)
		tempText = ""
		
		-- ########################
		-- extraText
		-- ########################
		Setup_ItemExtraText(self, nil, extraText, nil, nil)
		
		-- ########################
		-- itemTexture
		-- ########################
		if iconTexture == "?" then
			self:SetIcon("Interface\\Icons\\INV_Misc_QuestionMark")
		elseif iconTexture and type(iconTexture) == "string" and iconTexture ~= "" then
			self:SetIcon(iconTexture)
		else
			self:SetIcon(nil)
		end
		
		-- ########################
		-- Unsafe
		-- ########################
		self.Frame.Unsafe:Hide()
	end
end

--- Sets a link to the button
-- Sets a link to another loottable from AtlasLoot
-- @param lootTable Name of the AtlasLoot loottable
-- @usage AltasLootItemButton:SetLink(lootTable)
function AltasLootItemButton:SetLink(lootTable)
	if not lootTable or type(lootTable) ~= "string" then return end
	local dataID = AtlasLoot:FormatDataID(lootTable)
	if AtlasLoot_Data[dataID] or self.tableLinkFunc then
		self:SetButtonType("", "", lootTable)
		self:SetMenuButton(true)
	end
end
	
--- Shows or Hide the MenuButton
-- @param show true/false 
-- @usage AltasLootItemButton:SetMenuButton(show)
function AltasLootItemButton:SetMenuButton(show)
	if not show then
		self.Frame.Icon:Show()
		self.Frame.Icon:SetTexture(self.Frame.MenuIcon:GetTexture())

		self.Frame.MenuIcon:SetTexture(nil)
		self.Frame.MenuIcon:Hide()
		self.Frame.MenuIconBorder:Hide()
	else
		self.Frame.MenuIcon:Show()
		self.Frame.MenuIconBorder:Show()
		self.Frame.MenuIcon:SetTexture(self.Frame.Icon:GetTexture())
		
		self.Frame.Icon:Hide()
		self.Frame.Icon:SetTexture(nil)
	end
end

--- Sets a button Icon
-- @param icon the path to the icon
-- @usage AltasLootItemButton:SetIcon(icon)
function AltasLootItemButton:SetIcon(icon)
	if self.Frame.Icon:IsShown() then
		self.Frame.Icon:SetTexture(icon)
	elseif self.Frame.MenuIcon:IsShown() then
		self.Frame.MenuIcon:SetTexture(icon)
	end
end

--- Sets the level of an Heirloom item
-- @param lvl the level
function AltasLootItemButton:SetHeirloomLvl(lvl)
	self.cutomLvl = tonumber(lvl)
end
--- Querys the server
-- Querys the server for the setn item
-- @usage AltasLootItemButton:Query()
function AltasLootItemButton:Query()
	if self.info and self.info[2] and not self.info[1] then
		AtlasLootTooltip:SetHyperlink("item:"..self.info[2]..":0:0:0:0:0:0:0")
		self:Refresh()
	end
end
		
--- Clears the button
-- Clears and hides the itemButton
-- @usage AltasLootItemButton:Clear()
function AltasLootItemButton:Clear()
	self.Frame.Unsafe:Hide()
	self.Frame.QueryIcon:Hide()
	self:SetButtonType(nil, nil, nil)
	self:SetMenuButton(false)
	self:SetIcon(nil)
	self.Frame.Name:SetText("")
	self.Frame.Extra:SetText("")
	self.info = nil
	self.cutomLvl = nil
	self.itemType = nil
	self.tableLinkFunc = nil
	self.Frame:Hide()
end

--- Refresh the button
-- Refreshs the button
-- @usage AltasLootItemButton:Refresh()
function AltasLootItemButton:Refresh()
	local tabLinkSave = self.tableLink
	
	if self.item == true and self.spell == false and self.info then
		self:SetItem(self.info[2], self.info[3], self.info[4], self.info[5], self.info[6], self.info[7])
	elseif self.item == true and self.spell == false and self.info then
		self:SetSpell(self.info[1], self.info[2], self.info[3], self.info[4], self.info[5], self.info[6])
	elseif self.item == false and self.spell == false and self.info then
		self:SetMenu(self.tableLink, self.info[3], self.info[4], self.info[5])
	end
	
	self:SetLink(self.tableLink)
end

--- Returns a Chatlink
-- Returns a item or SpellLink
-- @return The link of the spell/item or the name
-- @return The name of the spell/item 
-- @usage local link, name = AltasLootItemButton:GetChatLink()
function AltasLootItemButton:GetChatLink()
	if self.info and self.info[1] then
		return AtlasLoot:GetEnchantLink(self.info[1]), ""
	elseif self.info and self.info[2] then
		local itemInfo, itemLink = GetItemInfo(self.info[2])
		local color = strsub(self.Frame.Name:GetText(), 1, 10)
		local name = strsub(self.Frame.Name:GetText(), 11)
		if itemInfo then
			return itemLink, name
		else
			return name, name
		end
	end
end

--- DressUp the item
-- @usage AltasLootItemButton:DressUp()
function AltasLootItemButton:DressUp()
	if self.info and self.info[2] then
		local _,itemLink = GetItemInfo(self.info[2])
		if itemLink then
			DressUpItemLink(itemLink)
		end
	end
end

function AltasLootItemButton:SetItemType(itemType)
	self.itemType = itemType
end
--- Adds a item button function
-- @param func the function
-- @param name the name of the function ( AltasLootItemButton:<NAME>() )
-- @usage AtlasLoot:AddItemButtonTemplateFunc(func, name)
function AtlasLoot:AddItemButtonTemplateFunc(func, name)
	if not func or not name or type(func) ~= "function" then return end
	if not AltasLootItemButton[name] then
		AltasLootItemButton[name] = func
	end
end

-----------------------------
-- Quests/Achievements Script functions
-----------------------------
function AtlasLoot:QAItemOnEnter()
	if not AtlasLootTooltip then AtlasLoot:SetupTooltip() end
	AtlasLootTooltip:ClearLines();
	for i=1, 30, 1 do
		if (_G["AtlasLootTooltipTextRight"..i] ~= nil) then
			_G["AtlasLootTooltipTextRight"..i]:SetText("");
		end
	end
	
	local questID = self.questID
	local achievementID = self.achievementID
	
	if questID then
		AtlasLootTooltip:SetOwner(self, "ANCHOR_RIGHT", -(self:GetWidth() / 2), 24);
		AtlasLootTooltip:SetHyperlink("quest:"..questID)
		AtlasLootTooltip:Show();
	elseif achievementID and GetAchievementLink(achievementID) then
		AtlasLootTooltip:SetOwner(self, "ANCHOR_RIGHT", -(self:GetWidth() / 2), 24);
		AtlasLootTooltip:SetHyperlink(GetAchievementLink(achievementID))
		AtlasLootTooltip:Show();
	end
end

function AtlasLoot:QAItemOnLeave()
	AtlasLootTooltip:Hide()
	GameTooltip:Hide()
	ShoppingTooltip2:Hide()
	ShoppingTooltip1:Hide()
end

function AtlasLoot:QAItemOnClick(arg1)
	if IsShiftKeyDown() then
		local questID = self.questID
		local achievementID = self.achievementID
		local link
		if questID then
			link = "|cffffff00|Hquest:"..questID.."|h["..AtlasLoot:GetQuestName(questID).."]|h|r"
			--/script DEFAULT_CHAT_FRAME:AddMessage("\124cffffff00\124Hquest:2969:47\124h[Freedom for All Creatures]\124h\124r");
			--http://www.wowpedia.org/QuestLink
		elseif achievementID then
			link = GetAchievementLink(achievementID)
		end
		if link then
			if ChatFrameEditBox and ChatFrameEditBox:IsVisible() then
				ChatFrameEditBox:Insert(link)
			else
				ChatEdit_InsertLink(link)
			end
		end
	end
end

-----------------------------
-- itemButton Script functions
-----------------------------
-- Tooltip
do
	local curEnter 

	-- http://www.wowwiki.com/Events/M#MODIFIER_STATE_CHANGED
	function onEvent(self, event, arg1, arg2)
		if curEnter then
			-- arg2: 1 for pressed, 0 (not nil!) for released 
			if arg2 == 1 then
				if arg1 == "LSHIFT" or arg1 == "RSHIFT" then
					AtlasLoot:ItemShowCompareItem()
				end
			else
				if arg1 == "LSHIFT" or arg1 == "RSHIFT" then
					ShoppingTooltip2:Hide()
					ShoppingTooltip1:Hide()
				end
			end
		end
	end

	local modifierStateFrame = CreateFrame("FRAME")
		modifierStateFrame:RegisterEvent("MODIFIER_STATE_CHANGED")
		modifierStateFrame:SetScript("OnEvent", onEvent)
	
	function AtlasLoot:SetupTooltip()
		if AtlasLootTooltip then AtlasLootTooltip:Hide() end
		if self.db.profile.UseGameTooltip then
			AtlasLootTooltip = GameTooltip
		else
			AtlasLootTooltip = AtlasLootTooltipTEMP
		end
	end

	-- Called when a loot item is moused over
	function AtlasLoot:ItemOnEnter()
		if not AtlasLootTooltip then AtlasLoot:SetupTooltip() end
		curEnter = true
		AtlasLootTooltip:ClearLines();
		for i=1, 30, 1 do
			if (_G["AtlasLootTooltipTextRight"..i] ~= nil) then
				_G["AtlasLootTooltipTextRight"..i]:SetText("");
			end
		end

		--self.info = { nil, itemID, itemName, extraText, itemTexture, itemPrice, itemDroprate }
		if not self.par.info then return end
		local spellID = self.par.info[1]
		local itemID = self.par.info[2]
		local droprate = self.par.info[7]
		
		
		if itemID and not spellID then
			if(itemID ~= nil) then
				if(GetItemInfo(itemID) ~= nil) then
					if _G[self:GetName().."_Unsafe"]:IsShown() then
						self.par:Refresh()
						return
					end
					--_G[self:GetName().."_Unsafe"]:Hide();
					AtlasLootTooltip:SetOwner(self, "ANCHOR_RIGHT", -(self:GetWidth() / 2), 24);
					if self.par.cutomLvl then
						AtlasLootTooltip:SetHyperlink("item:"..itemID..":0:0:0:0:0:0:0:"..self.par.cutomLvl);
						--AtlasLootTooltip:AddLine()
					else
						AtlasLootTooltip:SetHyperlink("item:"..itemID..":0:0:0");
						if select(3, GetItemInfo(self.par.info[2])) == 7 then
							AtlasLootTooltip:AddLine(ORANGE..AL["Shift + Right Click to select character level"])
						end
					end
					
					if ( AtlasLoot.db.profile.ItemIDs ) then
						AtlasLootTooltip:AddLine(BLUE..AL["ItemID:"].." "..itemID, nil, nil, nil, 1);
					end
					if( droprate ~= nil) and AtlasLoot.db.profile.DropRate then
						AtlasLootTooltip:AddLine(AL["Drop Rate: "]..droprate, 1, 1, 0);
					end
					if( DKP ~= nil and DKP ~= "" ) then
						AtlasLootTooltip:AddLine(RED..DKP.." "..AL["DKP"], 1, 1, 0);
					end
					if( priority ~= nil and priority ~= "" ) then
						AtlasLootTooltip:AddLine(GREEN..AL["Priority:"].." "..priority, 1, 1, 0);
					end
					
					AtlasLoot:AddTextToTooltip(AtlasLootTooltip, self.par.info)
					
					AtlasLootTooltip:Show();
					if((AtlasLoot.db.profile.EquipCompare and ((not EquipCompare_RegisterTooltip) or (not EquipCompare_Enabled)))) or IsShiftKeyDown() then
						AtlasLoot:ItemShowCompareItem(); --- CALL MISSING METHOD TO SHOW 2 TOOLTIPS (Item Compare)
					end
				else
					AtlasLootTooltip:SetOwner(self, "ANCHOR_RIGHT", -(self:GetWidth() / 2), 24);
					AtlasLootTooltip:ClearLines();
					
					AtlasLootTooltip:AddLine(RED..AL["Item Unavailable"], nil, nil, nil, 1);
					AtlasLootTooltip:AddLine(string.format(AL["|cff0070ddItemID: %d |r\nThis item is unsafe.  To view this item without the risk of disconnection, you need to have first seen it in the game world.\n\nYou can right-click to attempt to query the server.  You may be disconnected."],itemID), nil, nil, nil, 1)
					AtlasLootTooltip:Show();
					
				end
			end
		elseif spellID then
			AtlasLootTooltip:SetOwner(self, "ANCHOR_RIGHT", -(self:GetWidth() / 2), 24)
			AtlasLootTooltip:ClearLines()
			if AtlasLoot:GetEnchantLink(spellID) then
				AtlasLootTooltip:SetHyperlink(AtlasLoot:GetEnchantLink(spellID))
			end
			AtlasLootTooltip:Show()
			if(spellID and ((AtlasLoot.db.profile.EquipCompare and ((not EquipCompare_RegisterTooltip) or (not EquipCompare_Enabled))) or IsShiftKeyDown())) then
				AtlasLoot:ItemShowCompareItem() --- CALL MISSING METHOD TO SHOW 2 TOOLTIPS (Item Compare)
			end 
		end
	end

	-- Called when the mouse cursor leaves a loot item
	function AtlasLoot:ItemOnLeave()
		curEnter = nil
		AtlasLootTooltip:Hide()
		GameTooltip:Hide()
		ShoppingTooltip2:Hide()
		ShoppingTooltip1:Hide()
	end

	-- Missing GameToolTip method
	-- Enables item comparing. I've ripped self method directly from GameTooltip.lua and modified to work with AtlasLootTooltip /siena
	function AtlasLoot:ItemShowCompareItem()
		local shift = 1;
		local item,link = nil,nil
		if self.spellitemID and self.spellitemID ~= "" and self.spellitemID ~= 0 then
			item = AtlasLootTooltip:GetSpell()
			_,link = GetItemInfo(self.par.info[2])
		else
			item,link = AtlasLootTooltip:GetItem();
		end

		if ( not link ) then
			return
		end

		ShoppingTooltip1:SetOwner(AtlasLootTooltip, "ANCHOR_NONE");
		ShoppingTooltip2:SetOwner(AtlasLootTooltip, "ANCHOR_NONE");
		ShoppingTooltip3:SetOwner(AtlasLootTooltip, "ANCHOR_NONE");

		local item1 = nil;
		local item2 = nil;
		local item3 = nil;
		local side = "left";
		if ( ShoppingTooltip1:SetHyperlinkCompareItem(link, 1, 1, AtlasLootTooltip) ) then
			item1 = true;
		end
		if ( ShoppingTooltip2:SetHyperlinkCompareItem(link, 2, 1, AtlasLootTooltip) ) then
			item2 = true;
		end
		if ( ShoppingTooltip3:SetHyperlinkCompareItem(link, 3, 1, AtlasLootTooltip) ) then
			item3 = true;
		end
		if not item1 and not item2 and not item3 then 
			return 
		end

		if item3 then
			if not item1 then
				item1, item3 = true, nil;
				ShoppingTooltip1:SetHyperlinkCompareItem(link, 3, 1, AtlasLootTooltip);
			elseif not item2 then
				item2, item3 = true, nil;
				ShoppingTooltip2:SetHyperlinkCompareItem(link, 3, 1, AtlasLootTooltip);
			end
		end
		if item2 and not item1 then
			item1, item2 = true, nil;
			ShoppingTooltip1:SetHyperlinkCompareItem(link, 2, 1, AtlasLootTooltip);
		end

		local left, right, anchor1, anchor2 = AtlasLootTooltip:GetLeft(), AtlasLootTooltip:GetRight(), "TOPLEFT", "TOPRIGHT";
		if not left or not right then return end
		if (GetScreenWidth() - right) < left then anchor1, anchor2 = anchor2, anchor1 end

		if item1 then
			ShoppingTooltip1:ClearAllPoints();
			ShoppingTooltip1:SetPoint(anchor1, AtlasLootTooltip, anchor2, 0, -10);
			ShoppingTooltip1:Show();

			if item2 then
				ShoppingTooltip2:ClearAllPoints();
				ShoppingTooltip2:SetPoint(anchor1, ShoppingTooltip1, anchor2);
				ShoppingTooltip2:Show();
			end
			
			if item3 then
				ShoppingTooltip3:ClearAllPoints();
				ShoppingTooltip3:SetPoint(anchor1, ShoppingTooltip2, anchor2);
				ShoppingTooltip3:Show();
			end
		end
		
	end
	
end

-- Called when a loot item is clicked on
function AtlasLoot:ItemOnClick(arg1)
	local itemRarity
	if self.par.info and self.par.info[2] then
		itemRarity = select(3, GetItemInfo(self.par.info[2]))
	end
	if self.par.tableLink and arg1 == "LeftButton" and not IsAltKeyDown() then
		if self.par.tableLinkFunc then
			AtlasLoot:ShowLootPage(self.par.tableLinkFunc(self, self.par.tableLink))
		else
			AtlasLoot:ShowLootPage(self.par.tableLink)
		end
	elseif arg1 == "RightButton" and not IsShiftKeyDown() and not IsAltKeyDown() then
		self.par:Query()
	elseif IsShiftKeyDown() then
		if arg1 == "LeftButton" then
			local link, name = self.par:GetChatLink()
			if ChatFrameEditBox and ChatFrameEditBox:IsVisible() then
				ChatFrameEditBox:Insert(link)
			else
				ChatEdit_InsertLink(link)
			end
		elseif arg1 == "RightButton" and itemRarity and itemRarity == 7 and self.par.info then
			AtlasLoot:ShowHeriloomConfigWindow(self.par.info)
		end
	elseif IsControlKeyDown() then
		self.par:DressUp()
	end
end

-- HeriloomConfigWindow
do
	local AceGUI = LibStub("AceGUI-3.0")
	
	local curItemLvl = UnitLevel("player")
	
	local function onValueChanged(self, event, value)
		curItemLvl = value
		AtlasLoot.HeriloomConfigWindow.frame.itemButton:SetHeirloomLvl(value)
	end

	function AtlasLoot:ShowHeriloomConfigWindow(info)
		if self.HeriloomConfigWindow then
			curItemLvl = UnitLevel("player")
			AtlasLoot.HeriloomConfigWindow.frame.itemButton:SetHeirloomLvl(curItemLvl)
			self.HeriloomConfigWindow.frame:Show()
			self.HeriloomConfigWindow.frame.itemButton:SetItem(info[2], info[3], info[4], info[5], info[6], info[7])
			
			self.HeriloomConfigWindow.frame.Slider:SetValue(curItemLvl)
			self.HeriloomConfigWindow.frame.Slider:SetSliderValues(1, self:GetHeirloomMaxLvl(info[2]), 1) 
			--OnValueChanged
		else
			self.HeriloomConfigWindow = {}
			self.HeriloomConfigWindow.frame = CreateFrame("Frame","AtlasLoot_HeriloomConfigWindow",UIParent)
			local frame = self.HeriloomConfigWindow.frame
			frame:SetWidth(262)
			frame:SetHeight(120)
			frame:SetPoint("CENTER",UIParent,"CENTER",0,0)
			frame:EnableMouse()
			frame:SetMovable(true)
			frame:SetResizable(true)
			frame:SetFrameStrata("FULLSCREEN_DIALOG")
			--frame:SetScript("OnMouseDown", frameOnMouseDown)
			
			--frame:SetScript("OnHide",frameOnClose)
			--frame:SetMinResize(240,240)
			frame:SetToplevel(true)

			frame.textures = {}
			frame.textures.titlebg = frame:CreateTexture(nil, "BACKGROUND")
			frame.textures.titlebg:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Title-Background]])
			frame.textures.titlebg:SetPoint("TOPLEFT", 9, -6)
			frame.textures.titlebg:SetPoint("BOTTOMRIGHT", frame, "TOPRIGHT", -28, -24)
			
			frame.textures.dialogbg = frame:CreateTexture(nil, "BACKGROUND")
			--frame.textures.dialogbg:SetTexture([[Interface\Tooltips\UI-Tooltip-Background]])
			frame.textures.dialogbg:SetTexture(0, 0, 0, 1)
			frame.textures.dialogbg:SetPoint("TOPLEFT", 8, -24)
			frame.textures.dialogbg:SetPoint("BOTTOMRIGHT", -6, 8)
			--frame.textures.dialogbg:SetVertexColor(0, 0, 0, .75)
			
			frame.textures.topleft = frame:CreateTexture(nil, "BORDER")
			frame.textures.topleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.topleft:SetWidth(64)
			frame.textures.topleft:SetHeight(64)
			frame.textures.topleft:SetPoint("TOPLEFT")
			frame.textures.topleft:SetTexCoord(0.501953125, 0.625, 0, 1)
			
			frame.textures.topright = frame:CreateTexture(nil, "BORDER")
			frame.textures.topright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.topright:SetWidth(64)
			frame.textures.topright:SetHeight(64)
			frame.textures.topright:SetPoint("TOPRIGHT")
			frame.textures.topright:SetTexCoord(0.625, 0.75, 0, 1)
			
			frame.textures.top = frame:CreateTexture(nil, "BORDER")
			frame.textures.top:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.top:SetHeight(64)
			frame.textures.top:SetPoint("TOPLEFT", frame.textures.topleft, "TOPRIGHT")
			frame.textures.top:SetPoint("TOPRIGHT", frame.textures.topright, "TOPLEFT")
			frame.textures.top:SetTexCoord(0.25, 0.369140625, 0, 1)
			
			frame.textures.bottomleft = frame:CreateTexture(nil, "BORDER")
			frame.textures.bottomleft:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.bottomleft:SetWidth(64)
			frame.textures.bottomleft:SetHeight(64)
			frame.textures.bottomleft:SetPoint("BOTTOMLEFT")
			frame.textures.bottomleft:SetTexCoord(0.751953125, 0.875, 0, 1)
			
			frame.textures.bottomright = frame:CreateTexture(nil, "BORDER")
			frame.textures.bottomright:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.bottomright:SetWidth(64)
			frame.textures.bottomright:SetHeight(64)
			frame.textures.bottomright:SetPoint("BOTTOMRIGHT")
			frame.textures.bottomright:SetTexCoord(0.875, 1, 0, 1)
			
			frame.textures.bottom = frame:CreateTexture(nil, "BORDER")
			frame.textures.bottom:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.bottom:SetHeight(64)
			frame.textures.bottom:SetPoint("BOTTOMLEFT", frame.textures.bottomleft, "BOTTOMRIGHT")
			frame.textures.bottom:SetPoint("BOTTOMRIGHT", frame.textures.bottomright, "BOTTOMLEFT")
			frame.textures.bottom:SetTexCoord(0.376953125, 0.498046875, 0, 1)
			
			frame.textures.left = frame:CreateTexture(nil, "BORDER")
			frame.textures.left:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.left:SetWidth(64)
			frame.textures.left:SetPoint("TOPLEFT", frame.textures.topleft, "BOTTOMLEFT")
			frame.textures.left:SetPoint("BOTTOMLEFT", frame.textures.bottomleft, "TOPLEFT")
			frame.textures.left:SetTexCoord(0.001953125, 0.125, 0, 1)
			
			frame.textures.right = frame:CreateTexture(nil, "BORDER")
			frame.textures.right:SetTexture([[Interface\PaperDollInfoFrame\UI-GearManager-Border]])
			frame.textures.right:SetWidth(64)
			frame.textures.right:SetPoint("TOPRIGHT", frame.textures.topright, "BOTTOMRIGHT")
			frame.textures.right:SetPoint("BOTTOMRIGHT", frame.textures.bottomright, "TOPRIGHT")
			frame.textures.right:SetTexCoord(0.1171875, 0.2421875, 0, 1)
			
			frame.close = CreateFrame("Button", nil, frame, "UIPanelCloseButton")
			frame.close:SetPoint("TOPRIGHT", 2, 1)
			
			frame.titletext = frame:CreateFontString(nil, "ARTWORK")
			frame.titletext:SetFontObject(GameFontNormal)
			frame.titletext:SetPoint("TOPLEFT", 12, -8)
			frame.titletext:SetPoint("TOPRIGHT", -32, -8)
			frame.titletext:SetText(AL["Heirloom preview"])
			
			self.HeriloomConfigWindow.content = CreateFrame("Frame",nil,frame)
			self.HeriloomConfigWindow.content:SetPoint("TOPLEFT",frame,"TOPLEFT",12,-32)
			self.HeriloomConfigWindow.content:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",-12,13)

			frame.itemButton = AtlasLoot:CreateItemButton(frame, {"TOPLEFT", frame, "TOPLEFT", 13, -30}, "AtlasLootItem_HeirloomFrame")
			--frame.itemButton:SetItem(45038, "=q5=Fragment of Val'anyr", "=ds=#m3#", nil, nil, "40%")
			
			AceGUI:RegisterAsContainer(self.HeriloomConfigWindow)
			
			frame.Slider = AceGUI:Create("Slider")
			self.HeriloomConfigWindow:AddChild(frame.Slider)
			frame.Slider:SetWidth(236)
			frame.Slider:SetPoint("TOPLEFT", frame.itemButton.Frame, "BOTTOMLEFT")
			frame.Slider:SetCallback("OnValueChanged", onValueChanged)
			frame.Slider:SetLabel(AL["Change level:"])
			

			self:ShowHeriloomConfigWindow(info)
		end
	end

end
